<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="cart-header">
      <view class="header-left">
        <uni-icons type="arrowleft" size="24" color="#333" @click="goBack"></uni-icons>
        <text class="header-title">购物车</text>
      </view>
      <view class="header-right">
        <text @click="toggleEdit">{{ editMode ? '完成' : '编辑' }}</text>
      </view>
    </view>

    <!-- 空购物车提示 -->
    <view class="empty-cart" v-if="cartItems.length === 0">
      <uni-icons type="cart" size="80" color="#ccc"></uni-icons>
      <text class="empty-text">购物车空空如也</text>
      <button class="browse-btn" @click="goToHome">去逛逛</button>
    </view>

    <!-- 购物车商品列表 -->
    <view class="cart-list" v-else>
      <view class="section-title">我的购物车</view>
      <view class="cart-store" v-for="(store, index) in storeCarts" :key="index">
        <view class="store-header">
          <checkbox-group @change="storeSelect(store.id, $event)">
            <label class="checkbox-label">
              <checkbox :value="store.id" :checked="store.selected" color="#e54d42" />
              <text class="store-name">{{ store.name }}</text>
            </label>
          </checkbox-group>
        </view>

        <view class="cart-items">
          <view
              class="cart-item"
              v-for="(item, itemIndex) in store.items"
              :key="item.id"
              :class="{swiping: activeSwipe === item.id}"
          >
            <view class="swipe-content">
              <checkbox-group @change="itemSelect(item.id, $event)">
                <label class="checkbox-label">
                  <checkbox :value="item.id" :checked="item.selected" color="#e54d42" />
                </label>
              </checkbox-group>

              <image :src="item.image" class="item-image"></image>

              <view class="item-info">
                <view class="item-name">{{ item.name }}</view>
                <view class="item-sku">{{ item.sku }}</view>
                <view class="item-price-row">
                  <text class="item-price">¥{{ item.price }}</text>
                  <view class="stepper">
                    <button class="stepper-btn" @click="decreaseQty(item)">-</button>
                    <text class="item-quantity">{{ item.quantity }}</text>
                    <button class="stepper-btn" @click="increaseQty(item)">+</button>
                  </view>
                </view>
              </view>
            </view>

            <!-- 滑动操作区域 -->
            <view class="swipe-actions" @click="deleteItem(item)">
              <text class="delete-text">删除</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 推荐区域 -->
      <view class="recommend-section">
        <view class="section-header">
          <text class="section-title">猜你喜欢</text>
        </view>
        <view class="recommend-list">
          <view
              class="recommend-item"
              v-for="(item, index) in recommendedItems"
              :key="index"
              @click="addToCart(item)"
          >
            <image :src="item.image" class="recommend-image"></image>
            <view class="recommend-info">
              <view class="recommend-name">{{ item.name }}</view>
              <view class="recommend-price">¥{{ item.price }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 结算工具栏 -->
    <view class="settlement-bar" v-if="cartItems.length > 0">
      <view class="check-all">
        <checkbox-group @change="selectAll($event)">
          <label class="checkbox-label">
            <checkbox value="all" :checked="allSelected" color="#e54d42" />
            <text>全选</text>
          </label>
        </checkbox-group>
      </view>

      <view class="price-info" v-if="!editMode">
        <view class="total-price">
          合计：<text class="amount">¥{{ totalPrice }}</text>
        </view>
        <text class="freight">含运费：¥{{ shippingFee }}</text>
      </view>

      <view class="action-buttons">
        <button v-if="editMode" class="delete-btn" @click="deleteSelected">删除</button>
        <button v-else class="settlement-btn" @click="checkout">
          结算({{ selectedCount }})
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';

// 编辑模式
const editMode = ref(false);
// 当前滑动的商品ID
const activeSwipe = ref(null);

// 购物车数据
const storeCarts = reactive([
  {
    id: 's1',
    name: '迪漾DIANA美睫旗舰店',
    selected: false,
    items: [
      {
        id: 'i1',
        name: '经典-速干王胶水',
        sku: '速干王(1大瓶)',
        price: 120,
        image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=',
        quantity: 1,
        selected: true
      },
      {
        id: 'i2',
        name: 'LU0.07开花多根睫毛',
        sku: '山茶花睫毛 50元/盒起',
        price: 50,
        image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=',
        quantity: 2,
        selected: true
      }
    ]
  },
  {
    id: 's2',
    name: '美睫用品旗舰店',
    selected: false,
    items: [
      {
        id: 'i3',
        name: '仿真小绒花0.05睫毛',
        sku: '小红书爆款，狐系眼线款',
        price: 45,
        image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=',
        quantity: 1,
        selected: false
      }
    ]
  }
]);

// 推荐商品
const recommendedItems = reactive([
  {
    id: 'r1',
    name: '国风L婴儿弯睫毛',
    price: 45,
    image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk='
  },
  {
    id: 'r2',
    name: '黛毛上妆液',
    price: 78,
    image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk='
  },
  {
    id: 'r3',
    name: '假睫毛卸除液',
    price: 68,
    image: 'https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk='
  }
]);

// 获取所有购物车商品
const cartItems = computed(() => {
  return storeCarts.flatMap(store => store.items);
});

// 是否全选
const allSelected = computed(() => {
  return storeCarts.every(store => store.selected) &&
      cartItems.value.every(item => item.selected);
});

// 总价格
const totalPrice = computed(() => {
  return storeCarts.reduce((total, store) => {
    const storeTotal = store.items.reduce((sum, item) => {
      return item.selected ? sum + (item.price * item.quantity) : sum;
    }, 0);
    return total + storeTotal;
  }, 0);
});

// 运费
const shippingFee = computed(() => {
  const total = totalPrice.value;
  return total >= 200 ? 0 : 15;
});

// 选中的商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length;
});

// 切换编辑模式
const toggleEdit = () => {
  editMode.value = !editMode.value;
  // 重置滑动状态
  activeSwipe.value = null;
};

// 全选/取消全选
const selectAll = (e) => {
  const checked = e.detail.value.length > 0;
  storeCarts.forEach(store => {
    store.selected = checked;
    store.items.forEach(item => {
      item.selected = checked;
    });
  });
};

// 店铺选择
const storeSelect = (storeId, e) => {
  const checked = e.detail.value.length > 0;
  const store = storeCarts.find(s => s.id === storeId);
  if (store) {
    store.selected = checked;
    store.items.forEach(item => {
      item.selected = checked;
    });
  }
};

// 商品选择
const itemSelect = (itemId, e) => {
  const checked = e.detail.value.length > 0;
  cartItems.value.forEach(item => {
    if (item.id === itemId) {
      item.selected = checked;
    }
  });

  // 检查店铺是否全部选中
  storeCarts.forEach(store => {
    const allItemsSelected = store.items.every(item => item.selected);
    store.selected = allItemsSelected;
  });
};

// 增加数量
const increaseQty = (item) => {
  if (item.quantity < 99) {
    item.quantity++;
  }
};

// 减少数量
const decreaseQty = (item) => {
  if (item.quantity > 1) {
    item.quantity--;
  }
};

// 删除商品
const deleteItem = (itemToDelete) => {
  storeCarts.forEach(store => {
    store.items = store.items.filter(item => item.id !== itemToDelete.id);
  });

  // 删除空店铺
  for (let i = storeCarts.length - 1; i >= 0; i--) {
    if (storeCarts[i].items.length === 0) {
      storeCarts.splice(i, 1);
    }
  }
};

// 删除选中商品
const deleteSelected = () => {
  storeCarts.forEach(store => {
    store.items = store.items.filter(item => !item.selected);
  });

  // 删除空店铺
  for (let i = storeCarts.length - 1; i >= 0; i--) {
    if (storeCarts[i].items.length === 0) {
      storeCarts.splice(i, 1);
    }
  }
};

// 加入购物车
const addToCart = (product) => {
  // 查找商品是否已在购物车中
  const existingItem = cartItems.value.find(item => item.id === product.id);

  if (existingItem) {
    existingItem.quantity++;
  } else {
    // 添加到默认店铺
    storeCarts[0].items.push({
      ...product,
      id: `i${new Date().getTime()}`,
      sku: '默认型号',
      quantity: 1,
      selected: true
    });
  }

  uni.showToast({
    title: '已加入购物车',
    icon: 'success'
  });
};

// 结算
const checkout = () => {
  if (selectedCount.value === 0) {
    uni.showToast({
      title: '请选择要结算的商品',
      icon: 'none'
    });
    return;
  }

  uni.navigateTo({
    url: '/pages/order/confirm'
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 前往首页
const goToHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  });
};
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 100px;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.cart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  margin-left: 10px;
}

.header-right {
  color: #666;
  font-size: 16px;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 120px;
}

.empty-text {
  font-size: 16px;
  color: #999;
  margin: 20px 0;
}

.browse-btn {
  width: 200px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  color: #fff;
  background: linear-gradient(90deg, #e54d42, #d03a2f);
  font-size: 15px;
}

.cart-list {
  padding: 0 10px;
}

.section-title {
  font-size: 15px;
  font-weight: 500;
  padding: 16px 10px 10px;
  color: #333;
}

.cart-store {
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.store-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f5f5f5;
}

.checkbox-label {
  display: flex;
  align-items: center;
}

.store-name {
  font-size: 15px;
  font-weight: 500;
  margin-left: 8px;
}

.cart-items {
  padding: 0 16px;
}

.cart-item {
  position: relative;
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
  overflow: hidden;

  &.swiping .swipe-content {
    transform: translateX(-80px);
  }
}

.swipe-content {
  display: flex;
  align-items: center;
  width: 100%;
  transition: transform 0.3s ease;
}

.item-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  margin: 0 12px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-sku {
  font-size: 13px;
  color: #999;
  margin-bottom: 10px;
}

.item-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  color: #e54d42;
  font-size: 17px;
  font-weight: bold;
}

.stepper {
  display: flex;
  align-items: center;
}

.stepper-btn {
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  background-color: #f5f5f5;
  text-align: center;
  padding: 0;
  font-size: 18px;
}

.item-quantity {
  min-width: 35px;
  text-align: center;
  font-size: 16px;
}

.swipe-actions {
  position: absolute;
  top: 0;
  right: -80px;
  width: 80px;
  height: 100%;
  background-color: #e54d42;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-text {
  color: white;
  font-size: 15px;
}

.recommend-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin: 16px 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.section-header {
  padding-bottom: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.recommend-list {
  display: flex;
  flex-direction: column;
  margin-top: 16px;
}

.recommend-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.recommend-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  margin-right: 12px;
}

.recommend-name {
  font-size: 15px;
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 40px;
  line-height: 20px;
}

.recommend-price {
  color: #e54d42;
  font-size: 16px;
  font-weight: bold;
}

.settlement-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 12px 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.check-all {
  flex: 1;
}

.price-info {
  flex: 1;
  padding-right: 16px;
}

.total-price {
  font-size: 15px;
  margin-bottom: 3px;
  text-align: right;
}

.amount {
  color: #e54d42;
  font-weight: bold;
  font-size: 18px;
}

.freight {
  font-size: 12px;
  color: #999;
  display: block;
  text-align: right;
}

.action-buttons {
  width: 130px;
}

.delete-btn {
  background-color: #e54d42;
  color: white;
  border-radius: 30px;
  height: 46px;
  line-height: 46px;
  font-size: 16px;
  font-weight: 500;
  padding: 0;
}

.settlement-btn {
  background: linear-gradient(90deg, #e54d42, #d03a2f);
  color: white;
  border-radius: 30px;
  height: 46px;
  line-height: 46px;
  font-size: 16px;
  font-weight: 500;
  padding: 0;
}
</style>